
import { useNavigate } from 'react-router-dom';
import { NavBar } from 'react-vant';
import React, { memo } from 'react'
import './index.css';
// import NavBar from '@/components/navBar';
const Index = memo(() => {
    const joop = useNavigate()
    const Toast = () => {
        joop(-1)
    }

    const webSocket = new WebSocket("ws://192.168.2.108:3001");
    webSocket.onmessage = function (msg) {
        console.log("接收到新消息:" + msg.data);
        const oFriendItem = document.createElement('div');
        oFriendItem.className = 'friedns-item';
        const oSpan = document.createElement('span');
        oSpan.className = 'friedns';
        const message = document.createTextNode(msg.data);
        oSpan.appendChild(message);
        oFriendItem.appendChild(oSpan);
        (document.getElementById('chatContent') as HTMLElement).appendChild(oFriendItem);
    };
    webSocket.onclose = function () {
        console.log("关闭连接");
    };
    const sendBtn = () => {
        const str = (document.getElementById('content') as HTMLInputElement).value
        const oMeItem = document.createElement('div');
        oMeItem.className = 'me-item';
        const oSpan = document.createElement('span');
        oSpan.className = 'me';
        const msg = document.createTextNode((document.getElementById('content') as HTMLInputElement).value);
        oSpan.appendChild(msg);
        oMeItem.appendChild(oSpan);
        (document.getElementById('chatContent') as HTMLElement).appendChild(oMeItem);
        // 发送后清空消息框
        (document.getElementById('content') as HTMLInputElement).value = '';
        webSocket.send(str);
    }
    const closeBtn = () => {
        webSocket.close();
    }
    return (
        <div>
            <NavBar
                title="聊天室"
                leftText="返回"
                onClickLeft={() => Toast()}
            />

            <div className="chat-room">
                <div className='chat-content' id="chatContent">
                </div>
                <div className="chat-op">
                    <input type="text" id="content" />
                    <input type="button" value="发送" onClick={sendBtn} id="send" />
                    <input type="button" value="关闭" onClick={closeBtn} id="close" />
                </div>

            </div>

        </div>

    )
})

export default Index
